package cn.bossfriday.common.plugin;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Objects;

/**
 * PlugSpringContext
 *
 * @author chenx
 */
@Slf4j
public class PluginSpringContext {

    private static AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    private PluginSpringContext() {
        // do nothing
    }

    static {
        context.setClassLoader(Thread.currentThread().getContextClassLoader());
    }

    /**
     * initialize
     *
     * @param basePackages
     */
    public static void initialize(String... basePackages) {
        // 手动注册 PluginResourcePostProcessor
        context.getBeanFactory().addBeanPostProcessor(new PluginResourcePostProcessor());

        // scan & refresh
        context.scan(basePackages);
        context.refresh();
        log.info("PluginSpringContext.refresh() done");
    }

    /**
     * getBean
     */
    public static <T> T getBean(Class<T> clazz) {
        if (Objects.isNull(clazz)) {
            return null;
        }

        return context.getBean(clazz);
    }
}
